package www.dianbaozu.com.ui.server.channelDetail

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.util.Log
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.luck.picture.lib.decoration.WrapContentLinearLayoutManager
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nim.uikit.api.NimUIKit
import com.netease.nim.uikit.api.SessionHelper
import com.netease.nim.uikit.api.model.team.TeamDataChangedObserver
import com.netease.nim.uikit.api.model.team.TeamMemberDataChangedObserver
import com.netease.nim.uikit.common.ui.recyclerview.adapter.IRecyclerView
import com.netease.nim.uikit.common.ui.recyclerview.listener.SimpleClickListener
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import com.netease.nimlib.sdk.team.constant.TeamMemberType
import com.netease.nimlib.sdk.team.model.Team
import com.netease.nimlib.sdk.team.model.TeamMember
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentChannelDetailBinding
import www.dianbaozu.com.extension.requestUniversally
import www.dianbaozu.com.ui.server.channelDetail.adapter.ChannelDetailAdapter
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.RequestBodyParameter
import www.wen.com.common.lib.data.entities.ServiceMemberEntity
import www.wen.com.common.lib.extension.finishMyself
import www.wen.com.common.lib.extension.nav
import www.wen.com.common.lib.extension.navBack
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.util.WxUtil
import www.wen.com.common.lib.util.WxUtil.shareText
import www.wen.com.common.lib.view.ChannelDetailHeader

@AndroidEntryPoint
class ChannelDetailFragment : BaseLoadingFragment<FragmentChannelDetailBinding>(),
    View.OnClickListener {
    private val sessionId by lazy { requireActivity().intent.getStringExtra("sessionId") ?: "" }
    private val serverId by lazy { requireActivity().intent.getStringExtra("serverId") ?: "" }
    private val mIwxapi by lazy { WxUtil.getIWXAPI(requireActivity()) }

    private val titleBarAdapter: TitleBarUniversalAdapter by lazy {
        TitleBarUniversalAdapter(requireActivity(), mTeam.name, action = ::titleAction)
    }

    private val mTeam by lazy { NIMHelper.getTeam(sessionId) }

    private val onlineUserList = mutableListOf<ServiceMemberEntity>()
    private val offlineUserList = mutableListOf<ServiceMemberEntity>()

    private var isOnlineHeaderShowed = false
    private var isOfflineHeaderShowed = false

    private val channelDetailAdapter: ChannelDetailAdapter by lazy {
        ChannelDetailAdapter(
            dataBinding.rvChannel,
            mutableListOf()
        )
    }

    override fun actionLeft() {
        finishMyself()
    }

    private val channelDetailViewModel: ChannelDetailViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = channelDetailViewModel

    override fun getLayoutId(): Int = R.layout.fragment_channel_detail

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter {
        return titleBarAdapter
    }

    override fun lazyInitView() {
        dataBinding.apply {
            registerTeamUpdateObserver(true)
            rvChannel.adapter = channelDetailAdapter
            rvChannel.layoutManager = WrapContentLinearLayoutManager(requireActivity())
            rvChannel.addOnItemTouchListener(object : SimpleClickListener<IRecyclerView>() {
                override fun onItemClick(adapter: IRecyclerView?, view: View?, position: Int) {
                }

                override fun onItemLongClick(adapter: IRecyclerView?, view: View?, position: Int) {
                }

                override fun onItemChildClick(adapter: IRecyclerView?, view: View?, position: Int) {
                    val item = channelDetailAdapter.data[position]
                    if (item is ServiceMemberEntity) {
                        if (item.userId == NIMHelper.getUserAccount()) {
                            return
                        }
                        SessionHelper.showBottomDialog(
                            requireActivity(),
                            item.userId,
                            item.allowFriendFlag == "1",
                            item.onlineStatus
                        ) { view, _, _ ->
                            if (view.id == R.id.llTwo) {
                                finishMyself()
                            }
                        }
                    }
                }

                override fun onItemChildLongClick(
                    adapter: IRecyclerView?,
                    view: View?,
                    position: Int
                ) {
                }
            })

            val channelDetailHeader = ChannelDetailHeader(requireActivity())
            channelDetailHeader.setType(SessionHelper.currentChannelVO?.channelType ?: "")
            channelDetailHeader.setOnInviteClick { showInviteDialog() }
            channelDetailHeader.setOnMoveTopClick { nav(R.id.action_channelDetailFragment_to_toppingFragment) }
            channelDetailHeader.setOnSearchClick { nav(R.id.action_channelDetailFragment_to_findMemberFragment) }
            channelDetailHeader.setOnSettingClick { nav(R.id.action_channelDetailFragment_to_channelSettingFragment) }

            val userTeamMember = NIMHelper.getTeamMember(sessionId, NIMHelper.getUserAccount())
            when (userTeamMember?.type?.value) {
                TeamMemberType.Normal.value, TeamMemberType.Apply.value -> {
                    channelDetailHeader.enableSetting(false)
                }
                TeamMemberType.Manager.value, TeamMemberType.Owner.value -> {
                    channelDetailHeader.enableSetting(true)
                }
            }

            channelDetailAdapter.addHeaderView(channelDetailHeader)
        }
        getServerMemberList(serverId)
    }

    private fun showInviteDialog() {
        channelDetailViewModel.requestUniversally(
            viewModelScope = lifecycleScope,
            isShowToastTip = false,
            request = { appDataManage ->
                appDataManage.requestServerShareUrl(
                    RequestBodyParameter(serverId = serverId)
                )
            }
        ) { shareUrlEntity ->
            CreateXPopupHelper.createBottomSharePopupView(PopupViewEntity().apply {
                isShow = true
                context = requireActivity()
                address = shareUrlEntity.shareUrl
                resultCallBack = { view, address, popupView ->
                    when (view.id) {
                        R.id.tvAddress -> {
                            val clipboard =
                                requireActivity().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                            val clip = ClipData.newPlainText("simple text", address)
                            clipboard.setPrimaryClip(clip)
                            toast("复制成功")
                        }
                        R.id.llShareWeChat -> {
                            mIwxapi.shareText(address, false) {
                                popupView.dismiss()
                            }
                        }
                        R.id.llShareToFriends -> {
                            mIwxapi.shareText(address, true) {
                                popupView.dismiss()
                            }
                        }
                    }
                }
            })
        }
    }

    @FlowPreview
    fun getServerMemberList(serverId: String) {
        channelDetailAdapter.clearData()
        channelDetailViewModel.getServerMemberList(serverId) {
            if (it.data.content.isEmpty()) {
                return@getServerMemberList
            }
            it.data.content.forEach { serviceMemberEntity ->
                if (serviceMemberEntity.onlineStatus) {
                    onlineUserList.add(serviceMemberEntity)
                } else {
                    offlineUserList.add(serviceMemberEntity)
                }
            }

            val dataList = mutableListOf<Any>()
            if (onlineUserList.isNotEmpty()) {
                dataList.add("在线-${onlineUserList.size}")
            }
            dataList.addAll(onlineUserList.toList())

            if (offlineUserList.isNotEmpty()) {
                dataList.add("离线-${offlineUserList.size}")
            }
            dataList.addAll(offlineUserList.toList())
            channelDetailAdapter.setNewData(dataList)
        }
    }

    private fun updateTeamInfo(team: Team) {
        titleBarAdapter.mViewHolder.titleView.text = team.name
    }

    /**
     * 注册群信息更新监听
     *
     * @param register
     */
    private fun registerTeamUpdateObserver(register: Boolean) {
        NimUIKit.getTeamChangedObservable()
            .registerTeamDataChangedObserver(teamDataChangedObserver, register)
        NimUIKit.getTeamChangedObservable()
            .registerTeamMemberDataChangedObserver(teamMemberDataChangedObserver, register)
    }

    /**
     * 群资料变动通知和移除群的通知（包括自己退群和群被解散）
     */
    var teamDataChangedObserver: TeamDataChangedObserver = object : TeamDataChangedObserver {
        override fun onUpdateTeams(teams: List<Team>) {
            if (mTeam == null) {
                return
            }
            for (t in teams) {
                if (t.id == mTeam.id) {
                    updateTeamInfo(t)
                    break
                }
            }
        }

        override fun onRemoveTeam(team: Team) {
            if (team == null) {
                return
            }
            if (team.id == this@ChannelDetailFragment.mTeam.id) {
                updateTeamInfo(team)
            }
        }
    }

    /**
     * 群成员资料变动通知和移除群成员通知
     */
    var teamMemberDataChangedObserver: TeamMemberDataChangedObserver =
        object : TeamMemberDataChangedObserver {
            override fun onUpdateTeamMember(members: List<TeamMember>) {

            }

            override fun onRemoveTeamMember(member: List<TeamMember>) {
//                getServerMemberList(serverId)
            }
        }


    override fun onDestroy() {
        super.onDestroy()
        registerTeamUpdateObserver(false)
    }

}